package com.whisperly.echotalk.account;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Handler;
import android.os.LocaleList;
import android.os.Looper;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.whisperly.echotalk.bllmodel.CommonResponse;
import com.whisperly.echotalk.bllmodel.ResultBody;
import com.whisperly.echotalk.bllmodel.UpdatePasswordDto;
import com.whisperly.echotalk.bllmodel.UserWithChat;
import com.whisperly.echotalk.starryb.R;
import com.whisperly.echotalk.starryb.netWorkUtils.BlinkCallback;
import com.whisperly.echotalk.starryb.netWorkUtils.NetworkUtils;
import com.whisperly.echotalk.starryb.schemas.Login;
import com.whisperly.echotalk.starryb.utils.AppsManager;
import com.whisperly.echotalk.starryb.utils.GlobalData;
import com.whisperly.echotalk.starryb.utils.MD5Utils;

import java.util.Locale;

public class AccountPws extends AppCompatActivity {
    private UserWithChat user = new UserWithChat();
    private EditText old_password,new_password, confirm_new_password;;

    private Button change_password;
    private View loadingView;

    @Override
    protected void attachBaseContext(Context newBase) {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(newBase);
        String languageCode = prefs.getString("language", "en");
        super.attachBaseContext(updateResources(newBase, languageCode));
    }

    public Context updateResources(Context context, String languageCode) {
        Locale locale = new Locale(languageCode);
        Locale.setDefault(locale);

        Resources res = context.getResources();
        Configuration config = new Configuration(res.getConfiguration());
        config.setLocale(locale);
        LocaleList localeList = new LocaleList(locale);
        LocaleList.setDefault(localeList);
        config.setLocales(localeList);
        context = context.createConfigurationContext(config);
        return context;
    }
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.pws);
        AppsManager.addActivity(this);
        user = GlobalData.getUser();
        loadingView = getLayoutInflater().inflate(R.layout.layout_loading, null);

        old_password = findViewById(R.id.old_password);
        new_password = findViewById(R.id.new_password);
        confirm_new_password = findViewById(R.id.confirm_password);
        change_password = findViewById(R.id.change_password);
        change_password.setOnClickListener(v -> changePws());
        confirm_new_password.setOnFocusChangeListener((v, hasFocus) -> {
            if (!hasFocus) {
                if (!isValidConfirmPws(confirm_new_password.getText().toString())) {
                    confirm_new_password.setError(getString(R.string.The_new_password));
                }
            }
        });
    }
    private boolean isValidConfirmPws(String confirmPws) {
        return confirmPws.equals(confirm_new_password.getText().toString().trim());
    }

    private void changePws(){
        showLoading();
        new Handler(Looper.getMainLooper()).postDelayed(()->{
            String oldPassword = old_password.getText().toString().trim();
            String newPassword = new_password.getText().toString().trim();
            String confirmPassword = confirm_new_password.getText().toString().trim();

            if (oldPassword.isEmpty() || newPassword.isEmpty() || confirmPassword.isEmpty()){
                showChangeDialog(getString(R.string.Please_d_leave_it_blank),false);
                old_password.setError(getString(R.string.Please_d_leave_it_blank));
                new_password.setError(getString(R.string.Please_d_leave_it_blank));
                hideLoading();
                return;
            }
            if(!newPassword.equals(confirmPassword)){
                showChangeDialog(getString(R.string.The_new_password_same),false);
                confirm_new_password.setError(getString(R.string.The_new_password_same));
                hideLoading();
                return;
            }
            UpdatePasswordDto updatePasswordDto = new UpdatePasswordDto();
            updatePasswordDto.setObjectId(user.getObjectId());
            updatePasswordDto.setPassword(newPassword);
            updatePasswordDto.setOldPassword(oldPassword);
            NetworkUtils.updatePassword(updatePasswordDto, new BlinkCallback() {
                @Override
                public void onSuccess(ResultBody<?> response) {
                    if (response.getCode() == 200) {
                        CommonResponse data = (CommonResponse) response.getData();
                        if (data.getSuccess()) {
                            hideLoading();
                            showChangeDialog(getString(R.string.Modification_successful), true);
                            return;
                        }else {
                            if (data.getCode() == 1005){
                                hideLoading();
                                showChangeDialog(getString(R.string.Failed_to_modify),false);
                                return;
                            }

                            if (data.getCode() == 1006){
                                hideLoading();
                                showChangeDialog(getString(R.string.The_old_password_is_incorrect),false);
                                return;
                            }
                        }
                    }
                    hideLoading();
                    showChangeDialog(getString(R.string.Failed_to_modify),false);
                }

                @Override
                public void onFailure(Throwable throwable) {
                    hideLoading();
                    showChangeDialog(getString(R.string.Network_error),false);
                }
            });
        },1000);

    }

    private void showChangeDialog(String message,boolean flag) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.Prompt);
        builder.setMessage(message);
        builder.setPositiveButton(R.string.OK, (dialog, which) -> {
            if (flag) {
                Intent intent = new Intent(AccountPws.this, Login.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                startActivity(intent);
                finish();
                AppsManager.finishAll();
                dialog.dismiss();
            }
        });
        AlertDialog dialog = builder.create();
        dialog.show();
    }

    private void showLoading() {
        if (loadingView.getParent() == null) {
            ((ViewGroup) findViewById(android.R.id.content)).addView(loadingView);
            Log.d("LoginActivity", "Loading view added");
        }
    }

    private void hideLoading() {
        ((ViewGroup) findViewById(android.R.id.content)).removeView(loadingView);
    }
}
